<template>
  <div class="Blockeywords">
    <el-card shadow="hover">
      <div class="searchBox">
        <div>
          <el-input placeholder="请输入过滤词" v-model="filterWords">
            <template slot="prepend">过滤词</template>
          </el-input>
          <el-button class="btn" @click="keywordKeywordListBtn"
            >查找搜索</el-button
          >
        </div>
        <div class="addBox">
          <el-button class="btn" @click="dialogVisible = true"
            >新增过滤词</el-button
          >
          <!-- <el-button class="btn" >导出过滤词表</el-button> -->
        </div>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="过滤词">
          <template slot-scope="scope">{{ scope.row.keyword }}</template>
        </el-table-column>
        <el-table-column prop="address" label="操作" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button size="mini" @click="handleDel(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px">
        <!-- <el-button @click="toggleSelection(tableData)"
          >切换第二、第三行的选中状态</el-button
        > -->
        <el-button @click="toggleSelection()">删除选中</el-button>
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="page"
        :limit.sync="pageSize"
        @pagination="getList"
      />
    </el-card>
    <el-dialog title="新增过滤词" :visible.sync="dialogVisible" width="30%">
      <div class="dialogBox">
        <el-input placeholder="请输入内容" v-model="keywordSetkeyword">
          <template slot="prepend">输入过滤词</template>
        </el-input>
        <el-upload
          class="upload-demo"
          :http-request="upLoad"
          action
          :before-upload="beforeAvatarUpload"
          multiple
          :limit="3"
          :on-exceed="handleExceed"
          :file-list="fileList"
        >
          <el-button size="small" type="primary">点击上传文件</el-button>
          <!-- <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div> -->
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="keywordSetkeywordBtn"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // 分页
import {
  keywordKeywordList,
  keywordDel,
  keywordSetkeyword,
} from "@/api/operationManagement";
import { client } from "@/utils/oss.js";
import { ossToken } from "@/api/NotificationManagement";

export default {
  components: { Pagination },
  inject: ["reload"],
  data() {
    return {
      filterWords: "",
      keywordSetkeyword: "", //ADD
      tableData: [],
      multipleSelection: [],
      total: 0,
      page: 1, //页码
      pageSize: 10, //每页条数
      dialogVisible: false,
      fileList: [],
      fileTxt: "",
    };
  },
  methods: {
    //列表
    keywordKeywordList() {
      keywordKeywordList({
        keyWord: "",
        page: this.page,
        pageSize: this.pageSize,
      }).then((res) => {
        if (res.code == 0) {
          this.tableData = res.data.list;
          this.total = parseInt(res.data.total);
        }
      });
    },
    //搜索
    keywordKeywordListBtn() {
      keywordKeywordList({
        keyWord: this.filterWords,
        page: 1,
        pageSize: this.pageSize,
      }).then((res) => {
        if (res.code == 0) {
          this.tableData = res.data.list;
          this.total = parseInt(res.data.total);
        }
      });
    },
    //添加
    keywordSetkeywordBtn() {
      if (this.keywordSetkeyword || this.fileTxt !== "") {
        keywordSetkeyword({
          keywords: this.keywordSetkeyword,
          file: this.fileTxt,
        }).then((res) => {
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: "添加成功",
            });
            this.reload();
            this.dialogVisible = false;
          }
        });
      } else {
        this.$message({
          type: "info",
          message: "添加不能为空",
        });
      }
    },
    //编辑
    handleEdit(row) {
      console.log(index, row);
    },
    // 删除
    handleDel(obj) {
      // console.log(obj.keyword);
      this.$confirm("此操作将永久删, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          keywordDel({
            keywords: obj.keyword,
          }).then((res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: "删除成功",
              });
              this.getList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //删除
    toggleSelection() {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (this.multipleSelection.length != 0) {
            this.multipleSelection.forEach((item) => {
              keywordDel({
                keywords: item.keyword,
              }).then((res) => {
                if (res.code == 0) {
                  this.$message({
                    type: "success",
                    message: "删除成功",
                  });
                }
                this.getList();
              });
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });

      // if (rows) {
      //   rows.forEach((row) => {
      //     this.$refs.multipleTable.toggleRowSelection(row);
      //     keywordDel({
      //       keywordDel: this.$refs.multipleTable.toggleRowSelection(row),
      //     }).then((res) => {
      //       if (res.code == 0) {
      //         this.$message({
      //           type: "success",
      //           message: "删除成功",
      //         });
      //         this.reload();
      //       }
      //     });
      //   });
      // } else {
      //   this.$refs.multipleTable.clearSelection();
      // }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeAvatarUpload(file) {
      const isTXT = file.type === "text/plain";
      if (!isTXT) {
        this.$message.error("上传文件只能是 TXT 格式!");
      }
      return isTXT;
    },
    //覆盖默认的上传行为，自定义上传的实现
    async upLoad(file) {
      await ossToken({
        type: 7, //txt
      }).then((res) => {
        if (res.code == 0) {
          this.dataObj = {
            accessKeyId: res.data.accessKey,
            accessKeySecret: res.data.accessSecret,
            securityToken: res.data.token,
            region: "oss-cn-hangzhou",
            bucket: res.data.bucket,
          };
        }
      });
      const self = this;
      let files = file.file;
      let point = files.name.lastIndexOf(".");
      let suffix = files.name.substr(point);
      let fileName = files.name.substr(0, point);
      let date = Date.parse(new Date());
      let fileNames = "/other/" + date / 1000 + suffix;
      console.log(fileNames);
      this.fileTxt = fileNames;
      // this.fileList = fileNames;
      //fileNames上传文件的名称
      //file.file上传文件的内容
      client(this.dataObj)
        .multipartUpload(fileNames, file.file)
        .then((result) => {
          //下面是如果对返回结果再进行处理，根据项目需要
          // console.log(result);
          self.$message({
            message: "上传成功",
            type: "success",
          });
        })
        .catch((err) => {
          self.$message.error("上传失败");
        });
    },
    //分页
    getList() {
      keywordKeywordList({
        keyWord: this.filterWords,
        page: this.page,
        pageSize: this.pageSize,
      }).then((res) => {
        if (res.code == 0) {
          this.tableData = res.data.list;
          this.total = parseInt(res.data.total);
        }
      });
    },
  },
  created() {
    this.keywordKeywordList();
  },
};
</script>

<style lang="less" >
.Blockeywords {
  margin: 30px;
  height: 100%;
  .searchBox {
    display: flex;
    justify-content: space-between;
    margin-bottom: 40px;
    div {
      display: flex;
      width: 50%;
      .el-input-group__prepend {
        width: 90px;
        line-height: 38px;
      }
      .el-input {
        margin-right: 10px;
      }
    }
    .addBox {
      display: flex;
      justify-content: flex-end;
      flex: 1;
    }
  }
  .dialogBox {
    .el-input {
      margin-bottom: 20px;
    }
  }
}
</style>